package com.example.sysao.controller;

import com.example.sysao.pejo.Admin;
import com.example.sysao.service.AdminService;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@Component
@RequestMapping("/admin")

//test
public class AdminController {
    @Resource
    private AdminService adminService;

    @RequestMapping("/checklogin")
    public Map<String, Object> login(int loginid, String pwd, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        Admin admin = adminService.findByIsandPwd(loginid);
        if (admin == null) {
            //
            map.put("success", false);
            map.put("msg", "账户不存在");
            return map;
        }
        if (!admin.getPassword().equals(pwd)) {
            map.put("success", false);
            map.put("msg", "密码错误");
            return map;
        }
        session.setAttribute("admin", admin);//保存用户登录状态
        map.put("userId", admin.getId());//将用户信息返回给前端
//        map.put("roleId", useriinfo.getRoleId());
        map.put("success", true);
        return map;
    }

    @RequestMapping("/saveadmin")
    public Map<String, Object> addSavefile(String userName, String email, String password, MultipartFile file, HttpSession session) throws IOException {
        //定义路径
        String basePath = "E:/uplode";
        SimpleDateFormat fmt = new SimpleDateFormat("yyyMMdd");
        String dateStr = fmt.format(new Date());//得到20030105
        String dir = basePath + "/" + dateStr;//存放的路径
        new File(dir).mkdirs();//生成目录保证有目录
        //取得后缀名，在拼接上唯一名称
        String fileType = StringUtils.getFilenameExtension(file.getOriginalFilename());//获得文件扩展名
        String localPath = "/" + dateStr + "/" + UUID.randomUUID() + "." + fileType;//UUID生成唯一的字符串
        LocalDateTime time = LocalDateTime.now();
        Admin admin = (Admin) session.getAttribute("admin");
        admin.setUserName(userName);
        admin.setPassword(password);
        admin.setEmail(email);
        admin.setPic(localPath.toLowerCase());

        String path = basePath + localPath;//绝对路径本地位置
        file.transferTo(new File(path));//文件通道保存
        Map<String, Object> map = new HashMap<>();
        if (adminService.saveAdmin(admin)) {
            map.put("success", true);
        }
        return map;
    }

    //判断是否在线
    @GetMapping("/online")
    public Map<String, Object> online(HttpSession session) {
        boolean online = session.getAttribute("admin") != null;
        Map<String, Object> map = new HashMap<>();
        map.put("success", online);
        return map;
    }

    @GetMapping("/logout")
    public Map<String, Object> logout(HttpSession session) {
        session.invalidate();//失效，清空数据
        Map<String, Object> map = new HashMap<>();
        map.put("success", true);
        return map;
    }

    @RequestMapping("/findadmin")
    public Admin findadmin(HttpSession session) {
        Admin admin = (Admin) session.getAttribute("admin");
        return admin;
    }


    @RequestMapping("/downlode/{id}")
    public ResponseEntity<FileSystemResource> downlode(@PathVariable("id") int id) throws UnsupportedEncodingException {
        //  SaveFile saveFile = saveFileService.findById(id);
        Admin admin = adminService.findByIsandPwd(id);
        if (admin != null) {
            String basePath = "E:/uplode";
            String Path = basePath + admin.getPic();//本地的路径
            File file = new File(Path);
            if (file.isFile()) {//文件存在
                //通知浏览器返回的是文件
                //设置消息头
                HttpHeaders headers = new HttpHeaders();
                String name = new String(admin.getUserName().getBytes(), "iso-8859-1");
                headers.add("Content-Type", "application/octet-stream");
                headers.add("Content-Disposition", "attachment; filename=" + admin.getUserName());
                return ResponseEntity.ok().headers(headers)
                        .contentLength(file.length()).body(new FileSystemResource(file));
            }
        }
        return null;
    }
}
